package cn.stylefeng.guns.modular.gridsystem.socketio;

import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.listener.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Server {
    private static final Logger logger = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) {
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9092);

        final SocketIOServer server = new SocketIOServer(config);

        server.addConnectListener(new ConnectListener() {
            public void onConnect(SocketIOClient client) {
                logger.info("Client connected: " + client.getSessionId());
            }
        });

        server.addDisconnectListener(new DisconnectListener() {
            public void onDisconnect(SocketIOClient client) {
                logger.info("Client disconnected: " + client.getSessionId());
            }
        });

        server.addEventListener("message", String.class, new DataListener<String>() {
            public void onData(SocketIOClient client, String data, AckRequest ackRequest) {
                logger.info("Received message: " + data);
                server.getBroadcastOperations().sendEvent("message", data);
            }
        });

        server.start();
        logger.info("Server started");

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                server.stop();
                logger.info("Server stopped");
            }
        }));
    }
}
